package com.atguigu.web;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

//public class UserServlet extends HttpServlet { //注释掉,是为了继承公共抽象类中的doPost()方法,该方法按照request.action,执行实现类的发射方法,执行时的对象,为实现类的实例对象"this"
public class UserServlet extends BaseServlet { //BaseServlet 就是公共抽象类
    private UserService userService=new UserServiceImpl();//本文件是web层,通过serice层,调用dao层,控制数据库
    User user=new User();

    protected void ajaxExistUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //System.out.println(request.getParameter("username"));
        Boolean existsUsername=userService.existUsername(request.getParameter("username"));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("existsUsername",existsUsername);
        Gson gson=new Gson();
        String mapToJson=gson.toJson(resultMap);
        response.getWriter().write(mapToJson);
        //request.getSession().invalidate();
        //response.sendRedirect(request.getContextPath());
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath());
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String token=(String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        String code=request.getParameter("code");//验证码
        String username=request.getParameter("username");
        String password=request.getParameter("password");

        if(token != null && token.equalsIgnoreCase(code)){
            user=WebUtils.CopyParamToBean(user,request.getParameterMap());//这一句是用来吧requset的内容打入得到对象中,进行mysql操作的简便实现方式
            User loginUser=userService.login(user);//利用BeanUtils.populate把参数放入user中,从而不用从request中提出参数,在把参数放入user中了
            if(loginUser==null){
                //System.out.println("写的什么记吧玩意,不对,重写");
                request.setAttribute("msg","写的什么记吧玩意,不对,重写");
                request.setAttribute("username",username);
                request.setAttribute("password",password);
                request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);//请求转发
            }else{
                request.getSession().setAttribute("user",loginUser);
                //System.out.println(loginUser);
                //request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
                response.sendRedirect(request.getContextPath()+"/serverServlet?action=list");
            }
        }else{
            //验证码为空,或不对
            request.setAttribute("msg","写的什么记吧玩意,不对,重写");
            request.setAttribute("username",username);
            request.setAttribute("password",password);
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);//请求转发
        }
//        //System.out.println(request.toString());//打印不出来,如何打印req内部信息
//        //request.setCharacterEncoding("UTF-8");
//        String username=request.getParameter("username");
//        System.out.println("UserServlet.java:27:username:"+username);
//        //username=new String(username.getBytes("ISO-8859-1"), "UTF-8");//http是8859格式的编码
//        String password=request.getParameter("password");

        //User user=new User();
//        try {
//            BeanUtils.populate(user,request.getParameterMap());//利用BeanUtils.populate把参数放入user中,从而不用从request中提出参数,在把参数放入user中了
//            //System.out.println(user);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
// post上来的数据,多半是要打入到user相似的对象中去.所以这个代码可以独立出去,最好写在接口中.也可以写成静态方法:这就是WebUtils类出现的原因
//        user=WebUtils.CopyParamToBean(user,request.getParameterMap());//这一句是用来吧requset的内容打入得到对象中,进行mysql操作的简便实现方式

        //User loginUser=userService.login(new User(null,username,password,null));//利用BeanUtils.populate把参数放入user中,从而不用从request中提出参数,在把参数放入user中了
//        User loginUser=userService.login(user);//利用BeanUtils.populate把参数放入user中,从而不用从request中提出参数,在把参数放入user中了
//        if(loginUser==null){
//            //System.out.println("写的什么记吧玩意,不对,重写");
//            request.setAttribute("msg","写的什么记吧玩意,不对,重写");
//            request.setAttribute("username",username);
//            request.setAttribute("password",password);
//            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);//请求转发
//        }else{
//            request.getSession().setAttribute("user",loginUser);
//            //System.out.println(loginUser);
//            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request,response);
//        }
    }
    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        System.out.println(request.getSession().getAttribute(KAPTCHA_SESSION_KEY));
        String token=(String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //System.out.println(request.toString());//打印不出来,如何打印req内部信息
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String repwd=request.getParameter("repwd");
        System.out.println("username:"+username);
//        String email=request.getParameter("email");
        String code=request.getParameter("code");//验证码

        request.setAttribute("username",username);
        request.setAttribute("password",password);
        request.setAttribute("repwd",repwd);
//        request.setAttribute("email",email);
        request.setAttribute("code",code);

        if(token != null && token.equalsIgnoreCase(code)){//验证码写死了,以后写活它
            //equalsIgnoreCase忽略大小写 别再用==了,low
            if(userService.existUsername(username)){
                System.out.println(username+"已存在");
                request.setAttribute("msg",username+"已存在");
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);//用户名已存在,所以需要用户用新用户名注册,于是让浏览器跳回注册页面
            }else{
                //userService.registUser(new User(null,username,password,email));

                // post上来的数据,多半是要打入到user相似的对象中去.所以这个代码可以独立出去,最好写在接口中.也可以写成静态方法:这就是WebUtils类出现的原因
                if(!password.equals(repwd)){
                    System.out.println("密码不一致");
                    request.setAttribute("msg","密码不一致");
                    request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
                }
                user=WebUtils.CopyParamToBean(user,request.getParameterMap());//这一句是用来吧requset的内容打入得到user对象中,进行mysql操作的简便实现方式
                userService.registUser(user);
                request.getSession().setAttribute("user",user);
                request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
            }
        }else {
            System.out.println(code);
            request.setAttribute("msg","验证码错误");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);//让用户重新注册,于是让浏览器返回一个注册页面
            //request.getRequestDispatcher()方法,是让浏览器跳回一个页面,一个静态页面.这个路径的出发点是项目的web目录
        }
    }
//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String action= request.getParameter("action");
////        if (action.equalsIgnoreCase("login")){
////            System.out.println("登录操作");
////            login(request,response);//这里把代码提到上面去,1,是为了使代码够清晰,2,是为了营造一个action是什么就执行什么方法的环境,为发射的运用做好准备
////            //反射,就是,用类的类对象,获取公布的方法中的某一个方法
////            //反射,还是,用类的类对象,获取公布的属性中的某个一个属性
////            //反射,还是,用类的类对象,获取公布的父类的父类数组成员们 (接口同理)
////            //反射,还是,用类的类对象,创造一个实例对象,并获取类对象的一个属性,属性set值进入实例对象,从而实例对象可以get到这个值的变化.
////                //这种操作,没有使用实例对象的set属性方法,而是用到了类对象的set属性方法,并指明了把这个属性给哪个实例对象.
////        }else{
////            System.out.println("注册操作");
////            regist(request,response);
////        }
//// 注释了用反射的方法
//        try {
//            Method method=UserServlet.class.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            method.invoke(this,request,response);//this表示当前的实例对象
//        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//            e.printStackTrace();
//        }
//    }
    //注释掉,是为了继承公共抽象类中的doPost()方法,该方法按照request.action,执行实现类的发射方法,执行时的对象,为实现类的实例对象"this"

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
